import React, { useState, useEffect, useCallback } from 'react';
import { Form, Input, Button, NavBar, Toast } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import axios, { AxiosResponse } from 'axios';

// 接口定义
interface ApiResponse<T=unknown> {
  code: number;
  msg?: string;
  data?: T;
  
}

// 表单状态类型
interface FormState {
  phone: string;
  password: string;
  confirmPassword: string;
  verifyCode: string;
}

// 倒计时hook
const useCountdown = (initialSeconds: number = 60) => {
  const [countdown, setCountdown] = useState(0);
  const [isRunning, setIsRunning] = useState(false);

  // 开始倒计时
  const start = useCallback(() => {
    setCountdown(initialSeconds);
    setIsRunning(true);
  }, [initialSeconds]);


  
  // 倒计时逻辑
  useEffect(() => {
    if (isRunning && countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown(prev => prev - 1);
      }, 1000);
      
      return () => clearTimeout(timer);
    } else if (countdown === 0) {
      setIsRunning(false);
    }
  }, [countdown, isRunning]);

  return {
    countdown,
    isRunning,
    start
  };
};

const Register: React.FC = () => {
  const navigate = useNavigate();
  const [formState, setFormState] = useState<FormState>({
    phone: '',
    password: '',
    confirmPassword: '',
    verifyCode: ''
  });
  const { countdown, isRunning, start } = useCountdown(60); // 设置倒计时60秒
  const [loading, setLoading] = useState(false);

  // 表单字段更新处理
  const handleChange = (field: keyof FormState) => (value: string) => {
    setFormState(prev => ({ ...prev, [field]: value }));
  };

  // 表单验证
  const validateForm = (): boolean => {
    const { phone, password, confirmPassword, verifyCode } = formState;

    // 手机号验证
    if (!phone.trim()) {
      Toast.show({ content: '请输入手机号', position: 'top' });
      return false;
    }

    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      Toast.show({ content: '请输入有效的手机号', position: 'top' });
      return false;
    }

    // 密码验证
    if (!password) {
      Toast.show({ content: '请输入密码', position: 'top' });
      return false;
    }

    if (password.length < 6) {
      Toast.show({ content: '密码长度至少为6位', position: 'top' });
      return false;
    }

    // 确认密码验证
    if (password !== confirmPassword) {
      Toast.show({ content: '两次输入的密码不一致', position: 'top' });
      return false;
    }

    // 验证码验证
    if (!verifyCode) {
      Toast.show({ content: '请输入验证码', position: 'top' });
      return false;
    }

    return true;
  };

  // 发送验证码
  const sendVerificationCode = async (): Promise<void> => {
    const { phone } = formState;
    
    if (isRunning || !phone) return;

    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      Toast.show({ content: '请输入有效的手机号', position: 'top' });
      return;
    }

    try {
      start(); // 启动倒计时
      const response: AxiosResponse<ApiResponse> = await axios.get('http://localhost:3000/login', { params: { phone } });
      
      if (response.data.code === 200) {
        Toast.show({ content: '验证码已发送', position: 'top' });
      } else {
        Toast.show({ content: response.data.msg || '验证码发送成功', position: 'top' });
        // 失败时重置倒计时
        // setCountdown(0);
      }
    } catch (error) {
      console.error('发送验证码错误:', error);
      Toast.show({ content: '网络错误，请稍后重试', position: 'top' });
      // 错误时重置倒计时
    //   setCountdown(0);
    }
  };
  
  // 注册处理
  const handleSubmit = async (): Promise<void> => {
    if (!validateForm()) return;

    setLoading(true);
    try {
      const { phone, password, verifyCode } = formState;
      const response: AxiosResponse<ApiResponse> = await axios.post('http://localhost:3000/register', {
        phone,
        password,
        verifyCode
      });

      if (response.data.code === 200) {
        Toast.show({ content: '注册成功', position: 'top' });
        setTimeout(() => navigate('/login'), 1500);
      } else {
        Toast.show({ content: response.data.msg || '注册失败', position: 'top' });
      }
    } catch (error) {
      console.error('注册错误:', error);
      Toast.show({ content: '网络错误，请稍后重试', position: 'top' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="container mx-auto px-4 py-8 max-w-md">
      <NavBar onBack={() => navigate(-1)}>用户注册</NavBar>

      <Form layout="horizontal" mode="card" className="mt-6">
        <Form.Item label="手机号">
          <Input
            placeholder="请输入手机号"
            value={formState.phone}
            onChange={handleChange('phone')}
            maxLength={11}
            type="tel"
          />
        </Form.Item>

        <Form.Item
          label="设置密码"
          help={formState.password && formState.password.length < 6 ? '密码长度至少为6位' : ''}
        >
          <Input
            placeholder="请输入密码"
            type="password"
            value={formState.password}
            onChange={handleChange('password')}
          />
        </Form.Item>

        <Form.Item
          label="确认密码"
          help={formState.password && formState.confirmPassword && formState.password !== formState.confirmPassword ? '两次输入的密码不一致' : ''}
        >
          <Input
            placeholder="请再次输入密码"
            type="password"
            value={formState.confirmPassword}
            onChange={handleChange('confirmPassword')}
          />
        </Form.Item>

        <Form.Item
          label="验证码"
          extra={
            <Button
              size="small"
              disabled={isRunning || !formState.phone}
              onClick={sendVerificationCode}
              style={{ color: isRunning ? '#bfbfbf' : '' }}
            >
              {isRunning ? `${countdown}秒后重发` : '获取验证码'}
            </Button>
          }
        >
          <Input
            placeholder="请输入验证码"
            value={formState.verifyCode}
            onChange={handleChange('verifyCode')}
            maxLength={6}
            type="number"
          />
        </Form.Item>
      </Form>

      <Button
        block
        shape="rounded"
        color="primary"
        onClick={handleSubmit}
        disabled={loading || !formState.phone || !formState.password || !formState.confirmPassword || !formState.verifyCode || formState.password.length < 6}
        loading={loading}
        className="mt-6"
      >
        注册
      </Button>
    </div>
  );
};

export default Register;  